package com.guavamail.smtp.command.impl;

import java.io.IOException;

import org.apache.mina.core.session.IoSession;

import com.guavamail.smtp.SMTPContext;
import com.guavamail.smtp.SMTPServerConfig;
import com.guavamail.smtp.SessionStatus;
import com.guavamail.smtp.auth.AuthenticationHandler;
import com.guavamail.smtp.auth.impl.DummyAuthenticationHandler;
import com.guavamail.smtp.command.AbstractCommand;
import com.guavamail.smtp.command.CommandHandler;

public class EHLO extends AbstractCommand {

	public EHLO() {
		super("EHLO", "");
	}

	@Override
	public void execute(String commandString, IoSession ioSession, SMTPContext ctx) throws IOException {
		String[] args = getArgs(commandString);
		if (args.length < 2) {
			sendResponse(ioSession, "501 Syntax: EHLO hostname");
			return;
		}

		SessionStatus sessionStatus = ctx.getSessionStatus();
		StringBuilder response = new StringBuilder();
		if (!sessionStatus.getHasSeenHelo()) {
			SMTPServerConfig cfg = ctx.getSMTPServerConfig();

			sessionStatus.setHasSeenHelo(true);
			response.append("250-");
			response.append(cfg.getHostName());
			response.append("\r\n");
			response.append("250-8BITMIME\r\n");

			if (CommandHandler.containsCommand(AUTH.VERB)) {
				getEhloString(ctx.getAuthenticationHandler(), response);
			}
			response.append("250 Ok");
		} else {
			String remoteHost = args[1];
			response.append("503 ");
			response.append(remoteHost);
			response.append(" Duplicate EHLO");
		}
		sendResponse(ioSession, response.toString());
	}

	private void getEhloString(AuthenticationHandler handler, StringBuilder sb) {
		if (!(handler instanceof DummyAuthenticationHandler)) {
			sb.append("250-").append(AUTH.VERB).append(' ');
			getTokenizedString(sb, handler.getAuthenticationMechanisms(), " ");
			sb.append("\r\n");
		}
	}
}
